# This file is part of telegram-purple
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02111-1301  USA
#
# Copyright Matthias Jentsch, Vitaly Valtman, Christopher Althaus, Markus Endres 2014-2017

srcdir=@srcdir@
prefix=@prefix@
datarootdir=@datarootdir@
localedir=@localedir@
gettext_package=@GETTEXT_PACKAGE@

# Also update mkwindows.sh
PIDGIN_VERSION=2.13.0
WIN32_GTK_BUNDLE_DIR=win32/gtk+-bundle_2.24.10-20120208_win32
WIN32_GTK_BUNDLE_URL=http://ftp.acc.umu.se/pub/gnome/binaries/win32/gtk+/2.24/gtk+-bundle_2.24.10-20120208_win32.zip
WIN32_GTK_BUNDLE_FILE=win32/gtk+-bundle_2.24.10-20120208_win32.zip
WIN32_PIDGIN_SRC_URL=http://sourceforge.net/projects/pidgin/files/Pidgin/${PIDGIN_VERSION}/pidgin-${PIDGIN_VERSION}.tar.gz/download
WIN32_PIDGIN_SRC_FILE=win32/pidgin-${PIDGIN_VERSION}.tar.gz
WIN32_PIDGIN_SRC_DIR=win32/pidgin-${PIDGIN_VERSION}
WIN32_PIDGIN_BIN_URL=http://sourceforge.net/projects/pidgin/files/Pidgin/${PIDGIN_VERSION}/pidgin-${PIDGIN_VERSION}-win32-bin.zip/download
WIN32_PIDGIN_BIN_FILE=win32/pidgin-${PIDGIN_VERSION}-win32-bin.zip
WIN32_PIDGIN_BIN_DIR=win32/pidgin-${PIDGIN_VERSION}-win32bin
WIN32_WEBP_URL=https://github.com/webmproject/libwebp/archive/v1.0.2.tar.gz
WIN32_WEBP_FILE=win32/libwebp-1.0.2.tar.gz
WIN32_WEBP_DIR=win32/libwebp-1.0.2
WIN32_DIRS=${WIN32_GTK_BUNDLE_DIR} ${WIN32_PIDGIN_SRC_DIR} ${WIN32_PIDGIN_BIN_DIR} ${WIN32_WEBP_DIR}
# Not directly used here, but the usage will be injected via the CFLAGS configure var.
# Note on webp: locally cross-built!  That's why it violates the pattern.
WIN32_INC=-I${WIN32_PIDGIN_SRC_DIR}/pidgin \
          -I${WIN32_PIDGIN_SRC_DIR}/pidgin/win32 \
          -I${WIN32_PIDGIN_SRC_DIR}/libpurple \
          -I${WIN32_PIDGIN_SRC_DIR}/libpurple/win32 \
          -I${WIN32_GTK_BUNDLE_DIR}/include \
          -I${WIN32_GTK_BUNDLE_DIR}/include/glib-2.0 \
          -I${WIN32_GTK_BUNDLE_DIR}/lib/glib-2.0/include \
          -I${WIN32_GTK_BUNDLE_DIR}/include/gtk-2.0 \
          -I${WIN32_GTK_BUNDLE_DIR}/lib/gtk-2.0/include \
          -Iobjs/webp/install/include
WIN32_CONTRIB_FILES=contrib/libgcrypt-20.dll contrib/libgpg-error-0.dll contrib/libgcc_s_dw2-1.dll

CFLAGS_INTL=-DENABLE_NLS -DLOCALEDIR='"$(localedir)"'
CFLAGS_WARN=-Wall -Wextra -Wno-deprecated-declarations -Wno-unused-parameter
CFLAGS_EXTRA=-I${srcdir} -I. -fno-strict-aliasing -fPIC -D_FORTIFY_SOURCE=2
CFLAGS=@CFLAGS@ @PURPLE_CFLAGS@ @DEFS@ ${CFLAGS_INTL} ${CFLAGS_WARN} ${CFLAGS_EXTRA}

LDFLAGS_EXTRA=-rdynamic -ggdb
LDFLAGS=@LDFLAGS@ @OPENSSL_LIBS@ @PURPLE_LIBS@ @LIBS@ ${LDFLAGS_EXTRA}

DIR_PERM=0755
FILE_PERM=0644

CC=@CC@
PKG_CONFIG=@PKG_CONFIG@
MSGFMT_PATH=@MSGFMT_PATH@

# Check if -fstack-protector-strong is supported before enabling it
STACK_PROTECTOR_UNSUPPORTED = $(shell $(CC) -fstack-protector-strong 2>&1 | grep -c 'stack-protector-strong')
ifeq "$(STACK_PROTECTOR_UNSUPPORTED)" "0"
	CFLAGS += -fstack-protector-strong
endif
# Check if -frandom-seed is supported before enabling it
RANDOM_SEED_UNSUPPORTED = $(shell $(CC) -frandom-seed=77e0418a98676b76729b50fe91cc1f250c14fd8f664f8430649487a6f918926d 2>&1 | grep -c 'random-seed')
ifeq "$(RANDOM_SEED_UNSUPPORTED)" "0"
	CFLAGS += -frandom-seed=0x$$(sha256sum $< | cut -f1 -d" ")
endif
# Check if -ffile-prefix-map is supported before enabling it
FILE_PREFIX_MAP_UNSUPPORTED = $(shell $(CC) -ffile-prefix-map=/foo/bar/baz=/quux 2>&1 | grep -c 'file-prefix-map')
ifeq "$(FILE_PREFIX_MAP_UNSUPPORTED)" "0"
	# FIXME
	CFLAGS += "-ffile-prefix-map=$(realpath ${srcdir})=telegram-purple"
endif

DEP=dep
EXE=bin
OBJ=objs
DIR_LIST=${DEP} ${EXE} ${OBJ} contrib

PLUGIN_OBJECTS=${OBJ}/tgp-net.o ${OBJ}/tgp-timers.o ${OBJ}/msglog.o ${OBJ}/telegram-base.o ${OBJ}/telegram-purple.o ${OBJ}/tgp-2prpl.o ${OBJ}/tgp-structs.o ${OBJ}/tgp-utils.o ${OBJ}/tgp-chat.o ${OBJ}/tgp-ft.o ${OBJ}/tgp-msg.o ${OBJ}/tgp-request.o ${OBJ}/tgp-blist.o ${OBJ}/tgp-info.o
ALL_OBJS=${PLUGIN_OBJECTS} ${EXTRA_OBJECTS}

ifdef MSGFMT_PATH
LOCALES=$(shell cat po/LINGUAS)
LOCALE_MOS=$(addprefix po/,$(addsuffix .mo,$(LOCALES)))
endif

.SUFFIXES:

.SUFFIXES: .c .h .o

PRPL_NAME=telegram-purple.so
PRPL_LIBNAME=${EXE}/${PRPL_NAME}
all: ${PRPL_LIBNAME} $(LOCALE_MOS)

PLUGIN_DIR_PURPLE=$(shell ${PKG_CONFIG} --variable=plugindir purple)
DATA_ROOT_DIR_PURPLE=$(shell ${PKG_CONFIG} --variable=datarootdir purple)
CRYPTO_FLAG=@CRYPTO_FLAG@


### == 'Magic' targets and infrastructure. == ###
# Here be dragons! See HACKING.BUILD.md
# for the full list of requirements, goals, and rationale.

.PHONY: create_dirs
create_dirs: ${DIR_LIST}

${DIR_LIST}:
	@test -d $@ || mkdir -p $@

DEPENDENCE=$(subst ${OBJ}/,${DEP}/,$(patsubst %.o,%.d,${ALL_OBJS}))
DEPENDENCE_LIST=${DEPENDENCE}
-include ${DEPENDENCE_LIST}

tgl/Makefile.in:
	@echo "tgl/Makefile.in not found. Maybe you need to 'git submodule update --init --recursive' ?" && exit 1

tgl/Makefile: tgl/Makefile.in Makefile
	cd tgl && ./configure -q ${CRYPTO_FLAG} --disable-extf CFLAGS="@CFLAGS@" LDFLAGS="@LDFLAGS@"

tgl/libs/libtgl.a: tgl/Makefile
	+${MAKE} -C tgl libs/libtgl.a

.PHONY: commit
commit:

# The *commands* for commit.h shall always be executed, but the
# *file* commit.h should only be considered to have changed in rare cases.
GIT_COMMIT=$(shell git rev-parse HEAD | cut -c1-10)
commit.h: commit
	@./commit.h.gen

# Ugly, but necessary, because otherwise commit.h would not get generated:
test/loadtest.c: commit.h

# Ugly, but necessary, because otherwise commit.h would not get generated:
telegram-purple.c: commit.h


### == 'Normal' build. == ###

${PLUGIN_OBJECTS}: ${OBJ}/%.o: ${srcdir}/%.c tgl/libs/libtgl.a | create_dirs
	echo $@ && ${CC} ${CFLAGS} ${CPPFLAGS} -I ${srcdir}/tgl -c -MP -MD -MF ${DEP}/$*.d -MQ ${OBJ}/$*.o -o $@ $<

po/%.mo: po/%.po
	${MSGFMT_PATH} -cf -o $@ $< >/dev/null 2>&1

${PRPL_LIBNAME}: ${ALL_OBJS} tgl/libs/libtgl.a | create_dirs
	${CC} -shared -o $@ $^ ${CFLAGS} ${LDFLAGS}


### == Translation fixes == ###
# I fucked up some of the language codes.
# Fixing it in Transifex would require me to recreate these groups,
# deleting all old translations and potentially losing the translators.
# This is ugly, but better than losing translators.
# The space in the matching pattern excludes the "Language-Team:" field.

po/de.po: po/de_DE.po
	sed -Ee 's/ de_DE/ de/' $< > $@

po/it.po: po/it_IT.po
	sed -Ee 's/ it_IT/ it/' $< > $@

po/pl.po: po/pl_PL.po
	sed -Ee 's/ pl_PL/ pl/' $< > $@

po/ru.po: po/ru_RU.po
	sed -Ee 's/ru_RU/ru/' $< > $@


### == noicon_{,un}install targets. Use only if you know that you don't need icons. Note that pidgin uses those files. == ###

.PHONY: noicon_install
noicon_install: $(PRPL_LIBNAME) $(LOCALE_MOS)
	mkdir -m $(DIR_PERM) -p $(DESTDIR)$(PLUGIN_DIR_PURPLE)
	install -m $(FILE_PERM) $(PRPL_LIBNAME) $(DESTDIR)$(PLUGIN_DIR_PURPLE)/$(PRPL_NAME)
	mkdir -m $(DIR_PERM) -p $(DESTDIR)/etc/telegram-purple
# Assume that the user does not use AppStream if she doesn't want icons
	@for lang in $(LOCALES); do \
		mkdir -p $(DESTDIR)$(localedir)/$$lang/LC_MESSAGES; \
		echo "installing po/$$lang.mo to $(DESTDIR)$(localedir)/$$lang/LC_MESSAGES/$(gettext_package).mo"; \
		install -m $(FILE_PERM) po/$$lang.mo $(DESTDIR)$(localedir)/$$lang/LC_MESSAGES/$(gettext_package).mo; \
	done

.PHONY: noicon_uninstall
noicon_uninstall:
	rm -f $(DESTDIR)$(PLUGIN_DIR_PURPLE)/$(PRPL_NAME)
	rm -f $(DESTDIR)/etc/telegram-purple/server.pub # TODO: Remove this in later versions
	rm -f $(DESTDIR)/etc/telegram-purple/server.tglpub # TODO: Remove this in later versions
# TODO: Delete all installed .mo's, no matter what LINGUAS says.
	@for lang in $(LOCALES); do \
		echo "removing $(localedir)/$$lang/LC_MESSAGES/$(gettext_package).mo"; \
		rm -f $(localedir)/$$lang/LC_MESSAGES/$(gettext_package).mo; \
	done


### == Main {,un}install targets. This should satisfy most needs. == ###

.PHONY: install
install: noicon_install
	mkdir -m $(DIR_PERM) -p $(DESTDIR)$(DATA_ROOT_DIR_PURPLE)/pixmaps/pidgin/protocols/16
	install -m $(FILE_PERM) imgs/telegram16.png $(DESTDIR)$(DATA_ROOT_DIR_PURPLE)/pixmaps/pidgin/protocols/16/telegram.png
	mkdir -m $(DIR_PERM) -p $(DESTDIR)$(DATA_ROOT_DIR_PURPLE)/pixmaps/pidgin/protocols/22
	install -m $(FILE_PERM) imgs/telegram22.png $(DESTDIR)$(DATA_ROOT_DIR_PURPLE)/pixmaps/pidgin/protocols/22/telegram.png
	mkdir -m $(DIR_PERM) -p $(DESTDIR)$(DATA_ROOT_DIR_PURPLE)/pixmaps/pidgin/protocols/48
	install -m $(FILE_PERM) imgs/telegram48.png $(DESTDIR)$(DATA_ROOT_DIR_PURPLE)/pixmaps/pidgin/protocols/48/telegram.png
	mkdir -m $(DIR_PERM) -p $(DESTDIR)$(datarootdir)/metainfo
	install -m $(FILE_PERM) AppStream/telegram-purple.metainfo.xml $(DESTDIR)$(datarootdir)/metainfo/telegram-purple.metainfo.xml

.PHONY: uninstall
uninstall: noicon_uninstall
	rm -f $(DESTDIR)$(DATA_ROOT_DIR_PURPLE)/pixmaps/pidgin/protocols/16/telegram.png
	rm -f $(DESTDIR)$(DATA_ROOT_DIR_PURPLE)/pixmaps/pidgin/protocols/22/telegram.png
	rm -f $(DESTDIR)$(DATA_ROOT_DIR_PURPLE)/pixmaps/pidgin/protocols/48/telegram.png
	rm -f $(DESTDIR)$(datarootdir)/appdata/telegram-purple.metainfo.xml # old location
	rm -f $(DESTDIR)$(datarootdir)/metainfo/telegram-purple.metainfo.xml # new location


### == The local_{,un}install targets, in case you're not root. == ###

.PHONY: local_install
local_install:
	mkdir -m $(DIR_PERM) -p $(DESTDIR)$(HOME)/.purple/plugins
	install -m $(FILE_PERM) $(PRPL_LIBNAME) $(DESTDIR)$(HOME)/.purple/plugins/$(PRPL_NAME)

.PHONY: local_uninstall
local_uninstall:
	rm -f $(DESTDIR)$(HOME)/.purple/plugins/$(PRPL_NAME)
	rm -f $(DESTDIR)$(HOME)/.purple/telegram-purple/server.tglpub # TODO: Remove this in later versions


### == Windows sources downloads == ###

.PHONY: download_win32_sources
download_win32_sources: | ${WIN32_DIRS}

win32:
	@mkdir -p $@

${WIN32_GTK_BUNDLE_DIR}: | ${WIN32_GTK_BUNDLE_FILE}
	unzip -q $| -d $@

${WIN32_GTK_BUNDLE_FILE}: | win32
	wget -q -O $@ ${WIN32_GTK_BUNDLE_URL}

${WIN32_PIDGIN_SRC_DIR}: | ${WIN32_PIDGIN_SRC_FILE}
	tar xf $| -C win32/

${WIN32_PIDGIN_SRC_FILE}: | win32
	wget -q -O $@ ${WIN32_PIDGIN_SRC_URL}

${WIN32_PIDGIN_BIN_DIR}: | ${WIN32_PIDGIN_BIN_FILE}
	unzip -q $| -d win32/

${WIN32_PIDGIN_BIN_FILE}: | win32
	wget -q -O $@ ${WIN32_PIDGIN_BIN_URL}

${WIN32_WEBP_DIR}: | ${WIN32_WEBP_FILE}
	tar xf $| -C win32/

${WIN32_WEBP_FILE}: | win32
	wget -q -O $@ ${WIN32_WEBP_URL}

.PHONY: win-installer-deps
win-installer-deps: telegram-purple.nsi $(PRPL_LIBNAME) $(LOCALE_MOS) ${WIN32_CONTRIB_FILES}
	@[ "x${PRPL_NAME}" = "xlibtelegram.dll" ] || { \
		echo "WARNING: Bad PRPL_NAME.  This probably won't work." ; \
		echo "         (The DLL file cannot be just renamed!)" ; }

/usr/%:
	@echo "You're missing the file $@"
	@echo "Try installing the appropriate of the following packages:"
	@echo "    libgcrypt-mingw-w64-dev"
	@echo "    libgpg-error-mingw-w64-dev"
	@echo "    gcc-mingw-w64-i686"
	@echo "Also, please file a bug report *EVEN IF THIS SOLVES THE ISSUE*,"
	@echo "as it should have been detected earlier."

contrib/libgcrypt-20.dll: /usr/i686-w64-mingw32/bin/libgcrypt-20.dll | contrib
	cp $< "$@"

contrib/libgpg-error-0.dll: /usr/i686-w64-mingw32/bin/libgpg-error-0.dll | contrib
	cp $< "$@"

contrib/libgcc_s_dw2-1.dll: /usr/lib/gcc/i686-w64-mingw32/*-win32/libgcc_s_dw2-1.dll | contrib
	cp $< "$@"


### == Handling and maintenance. Subject to rapid change, shouldn't be used in scripts. == ###

.PHONY: plugin
plugin: $(PRPL_LIBNAME)

.PHONY: strip
strip: $(PRPL_LIBNAME)
	$(STRIP) --strip-unneeded $(PRPL_LIBNAME)

.PHONY: build-nsi
build-nsi: telegram-purple.nsi

config.h:
	@echo "How did you manage to do that?"
	@echo "You probably want to call ./config.status first."
	@exit 1

telegram-purple.nsi: telegram-purple.nsi.awk telegram-purple.nsi.awk-in po/LINGUAS config.h
	awk -f telegram-purple.nsi.awk telegram-purple.nsi.awk-in > telegram-purple.nsi

.PHONY: run
run:
	pidgin -d | grep 'telegram\|plugin\|proxy'

.PHONY: debug
debug: install
	ddd pidgin

DIST_ERR_MSG="Working directory is not git clean.\
Run 'git status' to show what files are causing this.\
Please note that 'make dist' packages the state in git, not the one on your disk."

SUBMOD_ERR_MSG="Submodule tgl looks weird.\
Are all submodules properly initialized and updated?"

# Not PHONY
.git:
	@echo "Not in a git folder. Features that require git are disabled."; exit 1

.PHONY: check-clean
check-clean: .git
	@test "x" = x"$(git status --porcelain)" || (echo ${DIST_ERR_MSG}; exit 1)
	@test -r tgl/.git || (echo ${SUBMOD_ERR_MSG}; exit 1)

# Feel free to remove the "check-clean" dependency if you know what you're doing.
.PHONY: dist
dist: check-clean commit.h .git create_dirs
	./gen-origtar


### == Cleaning in various flavors == ###

.PHONY: clean-here
clean-here:
	rm -rf ${DIR_LIST} "$(PRPL_LIBNAME)" telegram-purple.nsi po/*.mo autom4te.cache AppStream/po/*.mo commit.h

-include test/Makefile

.PHONY: clean
clean: clean-here clean-test tgl/Makefile
	+${MAKE} -C tgl clean
